package com.example.demo.web.controller;

import com.example.demo.bean.Comment;
import com.example.demo.service.ICommentService;
import com.example.demo.utils.ExcelUtils;
import com.example.demo.utils.Message;
import com.example.demo.utils.MessageUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private ICommentService commentService;
    @ApiOperation(value = "导入到Excel中", notes = "注意！测试的时候请将地址粘贴到浏览器地址栏测试", produces = "application/octet-stream")
    @GetMapping("download")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "评论模块",paramType = "query"),
            @ApiImplicitParam(name = "content", value = "评论模块",paramType = "query"),
            })
    public void download(HttpServletResponse response,Long id,String content) throws Exception {
        //查询数据
        List<Comment> list = commentService.query(id,content);
        // 2. 将excel导出
        // 2.1 excel头部数据
        String[] headList = new String[] { "id", "内容", "时间", "基地", "状态"};
        // 2.2 属性
        String[] fieldList = new String[] { "id", "content", "commentTime", "floor", "status" };
        // 2.3 数据列，需要转化
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (Comment u : list) {
        // 每一行map相当于一行数据，一行数据中多列
         Map<String, Object> map = new HashMap<>();
            map.put("id", u.getId());
            map.put("content", u.getContent());
            map.put("commentTime", u.getCommentTime());
            map.put("floor", u.getFloor());
            map.put("status", u.getStatus());
        // dataList表示所有行
            dataList.add(map);
        }
        // 2.4 导出文件名
        String excelName = "comments";
        // 3. 调用工具方法导出Excel
        ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);

    }
    @GetMapping("query")
    public Message query(Long id,String content) {
        List<Comment> list = commentService.query(id,content);
        return MessageUtil.success(list);
    }

    @PostMapping("saveOrUpdate")
    public Message saveOrUpdate(Comment comment) {
        commentService.saveOrUpdate(comment);
        return MessageUtil.success("操作成功");
    }

    @DeleteMapping("deleteById")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="用户编号",required=true,paramType ="query")
    })
    public Message deleteById(@NotNull long id) {
        commentService.deleteById(id);
        return MessageUtil.success("删除成功");
    }
}
